import { parse as vueParse, transform as vueTransform } from '@vue/compiler-dom'


const KEY_DATA = 'data-v-inspector'
export async function compileSFCTemplate(
    { code, id, type },
) {
    const relativePath = id
    const result = await new Promise((resolve) => {
        switch (type) {
            case 'template': {
                const ast = vueParse(code, { comments: true })
                vueTransform(ast, {
                    nodeTransforms: [
                        (node) => {
                            if (node.type === 1) {
                                const insertPosition = node.props.length ? Math.max(...node.props.map(i => i.loc.end.offset)) : node.loc.start.offset + node.tag.length + 1
                                const { line, column } = node.loc.start
                                const content = ` ${KEY_DATA}="${relativePath}:${line}:${column}"`
                                s.prependLeft(
                                    insertPosition,
                                    content,
                                )
                            }
                        },
                    ],
                })

                break
            }


            default:
                break
        }

        resolve(s.toString())
    })

    return result
}
export default function viteDevInspector() {
    return {
        name: 'my-vue-plugin',
        enforce: 'pre',
        transform(code, id) {
            if (id.endsWith('.vue')) {
                return compileSFCTemplate({ code, id, type: 'template' })
            }
        },
    };
}
